<template>
  <div  style="flex: 90%; margin-top: 20px; margin-left: 20px">
    <input v-model="text" placeholder="Enter text to speak" />
    <button @click="speakText">Speak</button>

    <!-- el-upload 组件 关闭自动上传 auto-upload -->
    <el-upload
      ref="upload"
      action="api/plat/stockDayRecord/upload"  
      :auto-upload="true" 
      :on-change="handleChange"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      list-type="picture-card"
    >
      <i class="el-icon-plus"></i>
    </el-upload>

    <!-- 监听全局粘贴事件 -->
    <div @paste="handlePaste">
      <!-- 可以放置其他内容或保持为空 -->
       <img src="F:\uploads\002640.SZ20241203.png" width="1200" height="600"/>
    </div>
  </div>
</template>

<script>
import { countdownEmits, ElMessage } from "element-plus";
import axios from "axios";
export default {
  data() {
    return {
      text: '士兰微股价下跌2%'
    };
  },
  mounted() {
    // 监听全局粘贴事件
    document.addEventListener('paste', this.handlePaste);
    // 确保获取到所有的发音人
    window.speechSynthesis.onvoiceschanged = () => {
      this.voices = window.speechSynthesis.getVoices();
    };
  },
  beforeDestroy() {
    // 移除全局粘贴事件监听器，防止内存泄漏
    document.removeEventListener('paste', this.handlePaste);
  },
  methods: {
    // 处理粘贴事件
    handlePaste(event) {
      console.log('paste event:', event);
      alert('粘贴事件触发');
      const items = (event.clipboardData || window.clipboardData).items;
      let blob = null;

      // 遍历粘贴板中的所有项
      for (let i = 0; i < items.length; i++) {
        if (items[i].type.indexOf('image') !== -1) {
          blob = items[i].getAsFile();
          break;
        }
      }

      // 如果粘贴的内容中有图片，则创建一个文件并上传
      if (blob) {
        const file = new File([blob], 'pasted-image.png', { type: 'image/png' });
        this.uploadImage(file);
      }
    },

    // 手动添加文件到上传列表
    uploadImage(file) {
      alert("上传图片")
      // const uploadFiles = this.$refs.upload.uploadFiles;
      // const isExist = uploadFiles.some(f => f.name === file.name && f.size === file.size);

      // if (!isExist) {
      //   this.$refs.upload.handleStart(file); // 将文件添加到上传队列
      //   this.$refs.upload.submit(); // 提交上传
      // } else {
      //   this.$message.warning('图片已存在');
      // }
      const formData = new FormData();
      formData.append('file', file); // 将文件添加到FormData对象中

      axios.post('api/plat/stockDayRecord/upload', formData, {
            headers: {
              'Content-Type': 'multipart/form-data' // 设置请求头
            }
          })
          .then(response => {
            console.log('文件上传成功:', response.data);
          })
          .catch(error => {
            console.error('文件上传失败:', error);
          });
    },

    handleChange(file, fileList) {
      console.log('file changed:', file, fileList);
    },

    handleSuccess(response, file, fileList) {
      console.log('upload success:', response, file, fileList);
    },

    beforeUpload(file) {
      const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGorPNG) {
        this.$message.error('只能上传 JPG 或 PNG 格式的图片!');
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!');
      }
      return isJPGorPNG && isLt2M;
    },
    
    speakText() {
      if ('speechSynthesis' in window) {
        const utterance = new SpeechSynthesisUtterance(this.text);
        // 设置发音人（可选）
        if (window.speechSynthesis.getVoices().length > 0) {
          utterance.voice = window.speechSynthesis.getVoices()[0];
        }
        // 设置语速、音调和音量（可选）
        utterance.rate = 1; // 语速
        utterance.pitch = 1; // 音调
        utterance.volume = 1; // 音量

        window.speechSynthesis.speak(utterance);
      } else {
        alert('Your browser does not support the Web Speech API.');
      }
    }

  }
};
</script>

<style scoped>
/* 样式可以根据需要进行调整 */
</style>